package com.zhiwei.cppapp.utils;

import android.os.SystemClock;
import android.util.Log;

import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author lenovo
 * @date 2016/12/28 0028
 * Root工具类
 */

public class RootUtil {

    /**
     * 应用程序运行命令获取 Root权限，设备必须已破解(获得ROOT权限)
     *
     * @param command 命令：String apkRoot="chmod 777 "+getPackageCodePath(); rootCmd(apkRoot);
     * @return 应用程序是/否获取Root权限
     */
    public static boolean rootCmd(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 执行root权限级别的指令
     *
     * @param cmd
     * @return
     */
    public static String execCmd(String cmd) {
        return execCmd(cmd, null);
    }

    /**
     * 主板执行su命令
     *
     * @param command          指令
     * @param workingDirectory 指令对象文件，串口1，串口3
     * @return 执行的命令反馈。
     */
    private static String execCmd(String command, File workingDirectory) {
        if (command == null || (command = command.trim()).length() == 0)
            return null;
        if (workingDirectory == null)
            workingDirectory = new File("/");
        java.io.OutputStream out = null;
        java.io.InputStream in = null;
        java.io.InputStream err = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("su", null, workingDirectory);
            StringBuffer inString = new StringBuffer();
            StringBuffer errString = new StringBuffer();
            out = process.getOutputStream();

            out.write(command.endsWith("\n") ? command.getBytes() : (command + "\n").getBytes());
            out.write(new byte[]{'e', 'x', 'i', 't', '\n'});
            in = process.getInputStream();
            err = process.getErrorStream();
            while (in.available() > 0)
                inString.append((char) in.read());
            while (err.available() > 0)
                errString.append((char) err.read());
            Log.i("test", "执行su命令 " + inString.toString());
            return inString.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            closeStream(out);
            closeStream(in);
            closeStream(err);
        }
    }

    /**
     * 关机，等5秒才执行,需要做一些程序的关闭处理，比如service的stop，activity的关闭等等
     */
    public static void shutdown() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(5 * 1000);//休眠5秒，等待关机
                rootCmd("reboot -p");
                Log.i("test", "shutdown");
            }
        }).start();
    }

    /**
     * 关闭IO流
     *
     * @param closeable
     */
    private static void closeStream(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
